<template>
  <div>
    <a-modal
      :title="title"
      :width="1000"
      :visible="visible"
      :maskClosable="false"
      :confirmLoading="confirmLoading"
      :footer="false"
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="关闭"
    >
      <a-spin :spinning="confirmLoading">
        <a-form :form="form">
          <a-row>
            <a-col :span="8">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="车场选择">
                <a-select
                  @change="parkCodeChange"
                  v-decorator="['parkCode', {}]"
                  placeholder="请选择车场"
                  :options="parkCodeList"
                  :disabled="isGreyPark"
                />
              </a-form-item>
              <a-form-item :labelCol="labelCol" v-show="false" :wrapperCol="wrapperCol" label="车场名称">
                <a-input v-decorator="['parkName', {}]" placeholder="车场名称" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :labelCol="labelCol" v-show="isEdit" :wrapperCol="wrapperCol" label="月租编号">
                <span>{{ monthlyCardInfo.monthlyCode }}</span>
                <span :style="{'font-weight': '500', 'margin-left': '6px','color':monthlyStatusColor}">{{
                  monthlyStatusTranslate(monthlyCardInfo.monthlyStatus)
                }}</span>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="8">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="车主姓名">
                <a-input
                  placeholder="请输入车主姓名"
                  v-decorator="['carOwnerName', { rules: [{ required: true, message: '请输入车主姓名!' }] }]"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="部门/组织">
                <a-tree-select
                  v-decorator="['monthlyDepartmentId', { initialValue: '' }]"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="departTree"
                  @select="departTreeSelect"
                  placeholder="请选择部门/组织"
                  tree-default-expand-all
                >
                  <span slot="title" slot-scope="{ key, value }" style="color: #08c"> Child Node1{{ value }} </span>
                </a-tree-select>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="false" label="部门名称">
                <a-input placeholder="请输入部门名称" v-decorator="['monthlyDepartmentName', {}]" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="住房/房号">
                <a-input placeholder="请输入住房/房号" v-decorator="['address', {}]" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="8">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="月租套餐" style="margin-bottom: 0px">
                <a-row>
                  <a-col :span="22">
                    <!--                    v-decorator="['packageId', {}]"-->
                    <!--                    v-model="currentMontlyPackageId"-->
                    <a-select
                      placeholder="请选择月租套餐"
                      v-decorator="['packageId', {}]"
                      @select="monthlyPackageInfoSelect"
                      :options="monthlyPackageInfoList"
                      :disabled="isGreyPackageInfo"
                    >
                    </a-select>
                  </a-col>
                  <a-col :span="1"></a-col>
                  <a-col :span="1">
                    <a-popover
                      title="套餐详细信息"
                      v-if="
                        currentMontlyPackage !== undefined &&
                        currentMontlyPackage !== null &&
                        JSON.stringify(currentMontlyPackage) !== '{}'
                      "
                    >
                      <template slot="content">
                        <table class="contentDetail">
                          <tr>
                            <td>月租车辆类别：</td>
                            <td>{{ currentMontlyPackage.monthlyTypeName }}</td>
                          </tr>
                          <tr>
                            <td>车位数：</td>
                            <td>{{ currentMontlyPackage.bindingSpaceNumber }}</td>
                          </tr>
                          <tr>
                            <td>是否固定车位：</td>
                            <td>{{ currentMontlyPackage.fixedSpace === 1 ? '固定' : '不固定' }}</td>
                          </tr>
                          <tr>
                            <td>可绑定车辆数：</td>
                            <td>{{ currentMontlyPackage.bindingCarNumber }}</td>
                          </tr>
                          <tr>
                            <td>周期长度：</td>
                            <td>{{ '1' + (currentMontlyPackage.cycleLength === 1 ? '天' : '月') }}</td>
                          </tr>
                          <tr>
                            <td>收费金额：</td>
                            <td>{{ parseFloat(currentMontlyPackage.charges / 100).toFixed(2) }}元</td>
                          </tr>
                          <tr>
                            <td>满位处理方式：</td>
                            <td>{{ currentMontlyPackage.fullManageName }}</td>
                          </tr>
                          <tr>
                            <td>过期车辆类别：</td>
                            <td>{{ currentMontlyPackage.overdueTypeName }}</td>
                          </tr>
                          <tr>
                            <td>过期延期方式：</td>
                            <td>{{ currentMontlyPackage.overdueDelayWay === 1 ? '顺延' : '跳延' }}</td>
                          </tr>
                          <tr>
                            <td>允许办理起始时间：</td>
                            <td>{{ currentMontlyPackage.allowHandleStarting === 1 ? '是' : '否' }}</td>
                          </tr>
                          <tr>
                            <td>允许办理截至时间：</td>
                            <td>{{ currentMontlyPackage.allowHandleOf === 1 ? '是' : '否' }}</td>
                          </tr>
                          <tr>
                            <td>最大允许购周期数：</td>
                            <td>{{ maxCycleTranslate() }}</td>
                          </tr>
                          <tr>
                            <td>是否允许线上购买：</td>
                            <td>{{ currentMontlyPackage.bindingSpaceNumber === 1 ? '允许' : '禁止' }}</td>
                          </tr>
                          <tr>
                            <td>是否允许线上续费：</td>
                            <td>{{ currentMontlyPackage.bindingSpaceNumber === 1 ? '允许' : '禁止' }}</td>
                          </tr>
                        </table>
                      </template>

                      <a-icon v-if="!showHref" type="question-circle" :style="{ fontSize: '20px', color: '#1890ff' }" />
                    </a-popover>
                  </a-col>
                </a-row>
              </a-form-item>
              <a-form-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="月租套餐名称"
                v-show="false"
                style="margin-bottom: 0px"
              >
                <a-input v-decorator="['packageName', {}]" placeholder="月租套餐名称" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="通行权限">
                <a-select
                  placeholder="选择通行权限"
                  @change="throughAuthorityIdChange"
                  v-decorator="['throughAuthorityId', { initialValue: '' }]"
                  :options="permissionGroupList"
                  :disabled="isGreyGroup"
                >
                </a-select>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="false" label="通行权限名称">
                <a-input placeholder="选择通行权限名称" v-decorator="['throughAuthorityName', {}]"> </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="手机号码">
                <a-input placeholder="请输入手机号码" v-decorator="['telephone', {}]" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="">
              <p style="line-height: 15px; margin-left: 125px; margin-top: -7px; margin-bottom: -7px">
                <a v-if="showHref && !isEdit" href="javascript:void(0);" @click="toOpenMonthlyPackage()">{{
                  instruction
                }}</a>
              </p>
              <p v-if="!showHref" style="line-height: 15px; margin-left: 125px; margin-top: -7px; margin-bottom: -7px">
                {{ instruction }}
              </p>
            </a-form-item>
          </a-row>
          <a-row>
            <a-col :span="8">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注信息">
                <a-input placeholder="请输入备注" v-decorator="['remark', {}]" />
              </a-form-item>
            </a-col>

          </a-row>
          <a-row>
            <a-col :span="8">
              <a-form-item
                :labelCol="labelCol"
                v-show="showAllowHandleStarting"
                :wrapperCol="wrapperCol"
                label="起始时间"
              >
                <!--                -->
                <a-date-picker
                  format="YYYY-MM-DD"
                  @change="beginTimeChange"
                  :disabled="(disableBeginTime && !isEdit) || isEdit"
                  v-decorator="['beginTime', { rules: [{ required: true, message: '请选择起始时间!' }] }]"
                />
                <!--&lt;!&ndash;    :disabled-date="disabledStartDate"   :disable="disableBeginTime"     v-model="startValue"  showTime.defaultValue="00:00:00"     @openChange="handleStartOpenChange"       -->
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :labelCol="labelCol" v-show="showAllowHandleOf" :wrapperCol="wrapperCol" label="到期时间">
                <a-date-picker
                  format="YYYY-MM-DD"
                  @change="endTimeChange"
                  :disabled="(disableEndTime && !isEdit) || isEdit"
                  v-decorator="['endTime', { rules: [{ required: true, message: '请选择到期时间!' }] }]"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :labelCol="labelCol"
                v-if="showCharges && !isEdit"
                :wrapperCol="wrapperCol"
                label="月租金额(元)"
              >

                <a-input-number
                  placeholder="请输入月租金额"
                  style="width: 130px"
                  :min="0"
                  :max="9999999.99"
                  :precision="2"
                  v-decorator="['monthlyMoney', { rules: [{ required: true, message: '请输入月租金额!' }] }]"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="8">
<!--              <a-row>-->
                <a-col :span="8" style="text-align: right; margin-left: 20px">
                  <label
                    class="itemLabel"
                    title="车位信息"
                    style="color: black; font-size: 14px; vertical-align: middle"
                  >
                    <span style="margin-right: -4px" class="ant-form-item-required"></span>
                    车位信息</label
                  >
                </a-col>
                <a-col :span="12">

                  <a-select
                    v-if="!isEdit || (isEdit && JSON.stringify(currentMontlyPackage)!='{}' && currentMontlyPackage.bindingSpaceNumber > 1)"
                    :show-search="true"
                    placeholder="请选择车位信息"
                    :filter-option="filterOption"
                    :value="selectParkNumber"
                    style="width: 100%"
                    @change="parkNumberChange"
                  >
                    <a-select-option v-for="item in parkNumberSelectList" :key="item.value" :value="item.value">
                      {{ item.label }}
                    </a-select-option>
                  </a-select>

                  <a-input v-model="selectParkNumberName" :disabled="isEdit && JSON.stringify(currentMontlyPackage)!='{}' && currentMontlyPackage.bindingSpaceNumber === 1" v-if="isEdit && JSON.stringify(currentMontlyPackage)!='{}' && currentMontlyPackage.bindingSpaceNumber === 1"
                  >
<!--                    {{ selectParkNumberName }}-->
                  </a-input>
                </a-col>
                <a-col :span="2">
                  <a-button
                    style="margin-left: 2px; text-align: center"
                    v-show="JSON.stringify(currentMontlyPackage)!='{}' && currentMontlyPackage.bindingSpaceNumber > 1"
                    :disabled="isGrey"
                    @click="parkNumberAdd"
                  >
                    <a-icon type="plus" />
                  </a-button>
                </a-col>
<!--              </a-row>-->
            </a-col>
            <a-col :span="8">
              <a-row>
                <a-col :span="8" style="text-align: right; margin-left: 20px">
                  <label
                    class="itemLabel"
                    title="车牌号码"
                    style="color: black; font-size: 14px; vertical-align: middle"
                  >
                    <span style="margin-right: -4px" class="ant-form-item-required"></span>
                    车牌号码</label
                  >
                </a-col>
                <a-col :span="12">
                  <a-input placeholder="请输入车牌号" v-model="inputPlateNo"> </a-input>
                </a-col>
                <a-col :span="2">
                  <a-button
                    style="margin-left: 2px; text-align: center"
                    v-if="JSON.stringify(currentMontlyPackage) != '{}' && currentMontlyPackage.bindingCarNumber > 1"
                    :disabled="isGreyPlateNo"
                    @click="plateNoAdd"
                  >
                    <a-icon type="plus" />
                  </a-button>
                </a-col>
              </a-row>
            </a-col>
          </a-row>
          <a-row style="margin-top: 10px">
            <a-col :offset="1" :span="8">
              <a-table
                ref="table"
                size="middle"
                bordered
                :columns="parkNumberColumns"
                :dataSource="parkNumberList"
                v-if="JSON.stringify(currentMontlyPackage) != '{}' && currentMontlyPackage.bindingSpaceNumber > 1"
              >
                <span slot="action" slot-scope="text, record">
                  <a-dropdown>
                    <a-popconfirm title="确定删除吗?" @confirm="() => popParkNumber(record.id)">
                      <a :disabled="isGreyParkNumber">删除</a>
                    </a-popconfirm>
                  </a-dropdown>
                </span>
              </a-table>
            </a-col>
            <a-col :offset="1" :span="6">
              <a-table
                ref="table"
                size="middle"
                bordered
                :columns="plateNoColumns"
                :dataSource="plateNoList"
                v-if="JSON.stringify(currentMontlyPackage) != '{}' && currentMontlyPackage.bindingCarNumber > 1"
              >
                <span slot="action" slot-scope="text, record">
                  <a-dropdown>
                    <a-popconfirm title="确定删除吗?" @confirm="() => popPlateNo(record.plateNo)">
                      <a>删除</a>
                    </a-popconfirm>
                  </a-dropdown>
                </span>
              </a-table>
            </a-col>
          </a-row>
          <a-row style="margin-top: 20px">
            <a-col :span="8" align="right">
              <a-button style="width: 80px; height: 30px; font-size: 14px" @click="handleCancel">返回</a-button>
            </a-col>
            <a-col :span="8" align="center">
              <a-button type="primary" @click="handleReset" v-if="!isEdit">清空</a-button>
            </a-col>
            <a-col :span="3" align="left">
              <a-button type="primary" @click="handleOk">确定</a-button>
            </a-col>
            <a-col :span="5">
              <a-checkbox
                style="margin-right: 14px; margin-top: 5px"
                :checked="continueOpen"
                v-if="!isEdit"
                @change="continueOpenMonthly"
                >继续开通月租
              </a-checkbox>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </a-modal>

    <!--  下次入场生效/立即生效对话框-->
    <a-modal v-model="takeEffectVisible" title="提示" on-ok="handleOk">
      <template slot="footer">
        <a-button key="takeEffectCancel" @click="takeEffectCancel"> 取消 </a-button>
        <a-button key="takeEffectNext" type="primary" :loading="loading" @click="takeEffectNextOK">
          下次入场生效
        </a-button>
        <a-button key="takeEffectCurrent" type="primary" :loading="loading" @click="takeEffectCurrentOK">
          立即生效
        </a-button>
      </template>
      <p>{{ noticeMsg }}</p>
    </a-modal>
  </div>
</template>

<script>
import { getAction, httpAction, postAction } from '@/api/manage'
import { getMonthlyParkInfoList } from '@api/api'
import pick from 'lodash.pick'
import moment from 'moment'

export default {
  name: 'MonthlyCardInfoModal',
  data() {
    return {
      title: '操作',
      visible: false,
      form: this.$form.createForm(this),
      monthlyCardInfo: {},
      result: {},
      confirmLoading: false,
      monthlyPackageInfoList: [],
      departTree: [],
      permissionGroupList: [],
      parkNumberPagination: {
        current: 1,
        pageSize: 5,
        // pageSizeOptions: ['10', '20', '30'],
        pageSizeOptions: ['5'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      plateNoPagination: {
        current: 1,
        pageSize: 5,
        // pageSizeOptions: ['10', '20', '30'],
        pageSizeOptions: ['5'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      labelCol: {
        xs: { span: 8 },
        sm: { span: 8 },
        style: { textAlign: 'right', marginLeft: '20px' },
      },
      wrapperCol: {
        xs: { span: 14 },
        sm: { span: 14 },
        style: { textAlign: 'left' },
      },
      parkNumberColumns: [
        {
          title: '车位号',
          align: 'center',
          dataIndex: 'parkNumber',
        },
        {
          title: '所在区域',
          align: 'center',
          dataIndex: 'areaName',
        },
        {
          title: '操作',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      parkNumberList: [],
      parkNumberSelectList: [],
      plateNoColumns: [
        {
          title: '车牌号',
          align: 'center',
          dataIndex: 'plateNo',
        },
        {
          title: '操作',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      plateNoList: [],
      parkCodeList: [],
      url: {
        add: '/monthlyCardInfo/add',
        getParkFreeSpaceList: '/monthlyCardInfo/queryUnUseSpace',
        getMonthlyCardBindParkNumber: '/parkCar/parkNumber/newlist',
        getPermissionGroupList: '/permissionGroup/getPermissionGroup',
        getDepartmentList: '/monthlyDepartment/queryTreeList',
        getMonthlyPackageList: '/monthlyPackageInfo/getMonthlyPackageInfoList',
        getParkSpaceById: '/parkCar/parkNumber/queryById',
        getUpatePlateNoInfo: 'monthlyCardInfo/getUpatePlateNoInfo',
        getUpateCarPlaceInfo: 'monthlyCardInfo/getUpateCarPlaceInfo',
        delayConfirm: '/monthlyCardInfo/delayConfirm',
        judegeIsOpenMonthlyCar: '/monthlyCardInfo/queryCarInUse',
        getPackageInfo: '/monthlyPackageInfo/queryById',
        edit: '/monthlyCardInfo/edit',
      },
      validatorRules: {
        carOwnerName: {
          rules: [{ required: true, message: '请输入车主名称!' }],
        },
      },
      selectParkNumber: '',
      selectParkNumberName: '',
      addPlateNo: [],
      addParkNumber: [],
      addPlateNos: [],
      deletePlateNos: [],
      inputPlateNo: '',

      loading: false,
      takeEffectVisible: false,
      noticeMsg: '',

      httpurl: '',
      formData: {},
      method: '',

      bindingSpaceNumber: 0,
      bindingCarNumber: 0,

      showHref: false,
      instruction: '',

      currentMontlyPackage: {},

      isOpenMonthlyCarNoticeMsg: '',

      showAllowHandleStarting: false,
      showAllowHandleOf: false,
      showCharges: false,
      disableBeginTime: false,
      disableEndTime: false,
      endOpen: false,

      startValue: null,
      endValue: null,

      continueOpen: false,
      // showNotice: false,

      isGrey: false,
      isGreyPark: true,
      isGreyPlateNo: false,
      isGreyPackageInfo: false,
      isGreyGroup: false,
      isGreyBeginTime: false,
      isGreyEndTime: false,
      isGreyParkNumber: false,
      parkCode: '',

      iSMonthCycle: false,
      sourceplateNoList: {},

      isEdit: false,
      monthlyStatusText: ['正常', '报停', '注销', '过期'],

      popoverVisible: false,

      //月租状态颜色
      monthlyStatusColor:"#4b7902"
    }
  },
  mounted() {},
  methods: {
    monthlyStatusTranslate(monthlyStatus){
      // 1、正常 2、报停 3、注销 4、过期
      if(monthlyStatus===3){
        return "注销"
      }
      if(monthlyStatus===2){
        return "报停"
      }
      if(new Date()>new Date(this.monthlyCardInfo.endTime)){
        this.monthlyStatusColor="red"
        return "过期"
      }else{
        this.monthlyStatusColor="#4b7902"
        return "正常"
      }

    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().includes(input.toLowerCase())
      );
    },
    parkNumberChange(parkNumber){
      this.selectParkNumber=parkNumber
    },
    maxCycleTranslate() {
      if (
        this.currentMontlyPackage.maxCycle === '' ||
        this.currentMontlyPackage.maxCycle === null ||
        this.currentMontlyPackage.maxCycle === undefined
      ) {
        return ''
      } else {
        return this.currentMontlyPackage.maxCycle + (this.currentMontlyPackage.cycleLength === 1 ? '天' : '月')
      }
    },
    beginTimeChange(value) {
      this.form.setFieldsValue({ monthlyMoney: '' })
      var aa = moment(value).format('YYYY-MM-DD')
      var bb = moment(this.form.getFieldValue('endTime')).format('YYYY-MM-DD')
      // if(this.form.getFieldValue("endTime")!==undefined && this.form.getFieldValue("endTime")!==null &&this.form.getFieldValue("endTime")!=='') {
      if (!this.isEmpty(this.form.getFieldValue('endTime')) && !this.isEmpty(value)) {
        if (moment(value).format('YYYY-MM-DD') > moment(this.form.getFieldValue('endTime')).format('YYYY-MM-DD')) {
          this.$message.warning('起始时间不能大于到期时间')
          this.$nextTick(() => {
            this.form.setFieldsValue({ monthlyMoney: '' })
            this.form.setFieldsValue({ beginTime: '' })
          })
          return
        }

        let _self = this
        if (!_self.isEmpty(value) && typeof value != 'string') {
          if (_self.currentMontlyPackage.cycleLength == 1) {
            // 周期按天
            _self.postponeMonthly(
              _self.getDaysBetween(
                moment(value).format('YYYY-MM-DD'),
                moment(this.form.getFieldValue('endTime'), 'YYYY-MM-DD').format('YYYY-MM-DD')
              )
            )
            return
          }
          // 周期按月
          let endTime = moment(this.form.getFieldValue('endTime'), 'YYYY-MM-DD'),
            yearDiffer = endTime.format('YYYY') - value.format('YYYY'),
            beginTimeYear = value.format('YYYY'),
            beginTimeMonth = value.format('M'),
            beginTimeDate = value.format('DD'),
            endTimeYear = endTime.format('YYYY'),
            endTimeMonth = endTime.format('M'),
            endTimeDate = endTime.format('DD'),
            endTimeBeginTimeMonthDiffer = undefined

          if (beginTimeYear == endTimeYear) {
            endTimeBeginTimeMonthDiffer = parseInt(endTimeMonth) - parseInt(beginTimeMonth)
          } else if (beginTimeYear != endTimeYear) {
            console.log('---不相同年份---')
            endTimeBeginTimeMonthDiffer = Math.abs(beginTimeMonth - 12) + (yearDiffer - 1) * 12 + parseInt(endTimeMonth)
          }
          judgmentInDate()

          // 是否相同月份
          function judgmentInMonth() {
            if (beginTimeMonth == endTimeMonth) {
              console.log('相同月份')
              return true
            }
            return false
          }

          // 是否相同天
          function judgmentInDate() {
          if (beginTimeDate == endTimeDate) {
            console.log('---相同天数---')
            return
          } else {
            let monthDateDiffer = Math.abs(
              _self.mGetDate(endTimeYear, endTimeMonth) - _self.mGetDate(beginTimeYear, beginTimeMonth)
            )
            console.log(
              '---天数不相同---',
              +endTimeDate,
              beginTimeDate,
              monthDateDiffer,
              beginTimeDate - endTimeDate,
              monthDateDiffer,
            )
            if (
              _self.mGetDate(beginTimeYear, beginTimeMonth) > _self.mGetDate(endTimeYear, endTimeMonth) &&
              beginTimeDate > endTimeDate &&
              beginTimeDate - endTimeDate <= monthDateDiffer && endTimeDate == _self.mGetDate(endTimeYear, endTimeMonth)
            ) {

            } else if (+beginTimeDate - 1 == 0) {
              ++endTimeBeginTimeMonthDiffer
              if (_self.mGetDate(endTimeYear, endTimeMonth) != endTimeDate) {
                return
              }
            } else if (+beginTimeDate - 1 != endTimeDate) {
              return
            }
          }

          _self.postponeMonthly(endTimeBeginTimeMonthDiffer)
        }
        }
      }
    },
    // 选择结束日期计算金额
    endTimeChange(value) {
      // this.$nextTick(() => {
      this.form.setFieldsValue({ monthlyMoney: '' })
      // })

      if (this.isEmpty(this.form.getFieldValue('beginTime'))) {
        this.$nextTick(() => {
          this.form.setFieldsValue({ monthlyMoney: '' })
          this.form.setFieldsValue({ endTime: '' })
        })
        this.$message.warning('请先选择起始时间')
        return
      }
      if (!this.isEmpty(value) && !this.isEmpty(this.form.getFieldValue('beginTime'))) {
        if (moment(this.form.getFieldValue('beginTime')).format('YYYY-MM-DD') > moment(value).format('YYYY-MM-DD')) {
          this.$message.warning('到期时间不能小于起始时间')
          this.$nextTick(() => {
            this.form.setFieldsValue({ endTime: '' })
            this.form.setFieldsValue({ monthlyMoney: '' })
          })
          return
        }
      }
      let _self = this
      if (!_self.isEmpty(value) && typeof value != 'string') {
        if (_self.currentMontlyPackage.cycleLength == 1) {
          // 周期按天
          _self.postponeMonthly(
            _self.getDaysBetween(
              moment(this.form.getFieldValue('beginTime'), 'YYYY-MM-DD').format('YYYY-MM-DD'),
              value.format('YYYY-MM-DD')
            )
          )
          return
        }
        // 周期按月
        let beginTime = moment(this.form.getFieldValue('beginTime'), 'YYYY-MM-DD'),
          yearDiffer = value.format('YYYY') - beginTime.format('YYYY'),
          beginTimeYear = beginTime.format('YYYY'),
          beginTimeMonth = beginTime.format('M'),
          beginTimeDate = beginTime.format('DD'),
          endTimeYear = value.format('YYYY'),
          endTimeMonth = value.format('M'),
          endTimeDate = value.format('DD'),
          endTimeBeginTimeMonthDiffer = undefined

        if (beginTimeYear == endTimeYear) {
          endTimeBeginTimeMonthDiffer = parseInt(endTimeMonth) - parseInt(beginTimeMonth)
        } else if (beginTimeYear != endTimeYear) {
          console.log('---不相同年份---')
          endTimeBeginTimeMonthDiffer = Math.abs(beginTimeMonth - 12) + (yearDiffer - 1) * 12 + parseInt(endTimeMonth)
        }
        judgmentInDate()
        // 是否相同月份
        function judgmentInMonth() {
          if (beginTimeMonth == endTimeMonth) {
            console.log('相同月份')
            return true
          }
          return false
        }
        // 是否相同天
        function judgmentInDate() {
          if (beginTimeDate == endTimeDate) {
            console.log('---相同天数---')
            return
          } else {
            let monthDateDiffer = Math.abs(
              _self.mGetDate(endTimeYear, endTimeMonth) - _self.mGetDate(beginTimeYear, beginTimeMonth)
            )
            console.log(
              '---天数不相同---',
              +endTimeDate,
              beginTimeDate,
              monthDateDiffer,
              beginTimeDate - endTimeDate,
              monthDateDiffer,
            )
            if (
              _self.mGetDate(beginTimeYear, beginTimeMonth) > _self.mGetDate(endTimeYear, endTimeMonth) &&
              beginTimeDate > endTimeDate &&
              beginTimeDate - endTimeDate <= monthDateDiffer && endTimeDate == _self.mGetDate(endTimeYear, endTimeMonth)
            ){

            } else if (+beginTimeDate - 1 == 0) {
              ++endTimeBeginTimeMonthDiffer
              if (_self.mGetDate(endTimeYear, endTimeMonth) != endTimeDate) {
                return
              }
            } else if (+beginTimeDate - 1 != endTimeDate) {
              return
            }
          }

          _self.postponeMonthly(endTimeBeginTimeMonthDiffer)
        }
      }
    },
    /**
     * 计算两个日期之间的天数
     * @param dateString1  开始日期 yyyy-MM-dd
     * @param dateString2  结束日期 yyyy-MM-dd
     * @returns {number} 如果日期相同 返回一天 开始日期大于结束日期，返回0
     */
    getDaysBetween(dateString1, dateString2) {
      var startDate = Date.parse(dateString1)
      var endDate = Date.parse(dateString2) + 86400000
      if (startDate > endDate) {
        return 0
      }
      if (startDate == endDate) {
        return 1
      }
      var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000)
      return days
    },
    postponeMonthly(value) {
      // let date = new Date(this.params.beginTime)
      // let date = new Date(this.form.getFieldValue("beginTime"))
      // this.params.endTime = moment(this.countEndTime(date, value), 'YYYY-MM-DD')
      // this.params.monthly = value
      if (isNaN(value) || value == 0) {
        return
      }
      this.form.setFieldsValue({
        // monthlyMoney: parseInt(this.currentMontlyPackage.charges) * parseInt(value),
        monthlyMoney: parseFloat(this.currentMontlyPackage.charges / 100).toFixed(2) * parseInt(value),

        // endTime: this.params.endTime,
        // endTime: this.form.getFieldValue("endTime"),
      })
    },
    /**
     * 判断变量是否为空，
     * @param  {[type]}  param 变量
     * @return {Boolean}      为空返回true，否则返回false。
     */
    isEmpty(param) {
      if (param) {
        var param_type = typeof param
        if (param_type == 'object') {
          //要判断的是【对象】或【数组】或【null】等
          if (typeof param.length == 'undefined') {
            if (JSON.stringify(param) == '{}') {
              return true //空值，空对象
            }
          } else if (param.length == 0) {
            return true //空值，空数组
          }
        } else if (param_type == 'string') {
          //如果要过滤空格等字符
          var new_param = param.trim()
          if (new_param.length == 0) {
            //空值，例如:带有空格的字符串" "。
            return true
          }
        } else if (param_type == 'boolean') {
          if (!param) {
            return true
          }
        } else if (param_type == 'number') {
          if (!param) {
            return true
          }
        }
        return false //非空值
      } else {
        //空值,例如：
        //(1)null
        //(2)可能使用了js的内置的名称，例如：var name=[],这个打印类型是字符串类型。
        //(3)空字符串''、""。
        //(4)数字0、00等，如果可以只输入0，则需要另外判断。
        return true
      }
    },
    // 获取当前月的天数
    mGetDate(year, month) {
      var d = new Date(year, month, 0)
      return d.getDate()
    },
    noticeClick() {
      if (!this.popoverVisible) {
        this.popoverVisible = true
      } else {
        this.popoverVisible = false
      }
    },
    continueOpenMonthly(e) {
      this.continueOpen = e.target.checked
    },
    toOpenMonthlyPackage() {
      this.$router.push({
        path: '/parking/parkmonthly/MonthlyPackageInfoList',
        query: {},
      })
    },
    takeEffectCancel() {
      this.takeEffectVisible = false
    },
    takeEffectNextOK() {
      this.loading = true
      //下次入场生效
      this.formData.isEffect = 2
      this.openMonthlyCard()
    },
    takeEffectCurrentOK() {
      this.loading = true
      //立即生效
      this.formData.isEffect = 1
      this.openMonthlyCard()
    },
    handleReset() {
      this.reset()
      this.initParkInfoList()
      this.visible = true
    },
    departTreeSelect(a, b) {
      let monthlyDepartmentName = b._props.title
      this.form.setFieldsValue({ monthlyDepartmentName: monthlyDepartmentName })
    },
    popPlateNo(plateNo) {
      this.addPlateNo.splice(
        this.addPlateNo.findIndex((item) => item === plateNo),
        1
      )
      this.plateNoList.splice(
        this.plateNoList.findIndex((item) => item.plateNo === plateNo),
        1
      )

      if (this.monthlyCardInfo.id != null && this.monthlyCardInfo.id != '') {
        // 添加要清除的车牌号
        if (this.deletePlateNos.indexOf(plateNo) == -1) {
          this.deletePlateNos.push(plateNo)
        }
        // 清除修改中要删除的车牌号
        this.addPlateNos.splice(
          this.addPlateNos.findIndex((item) => item === plateNo),
          1
        )
      }

      // 判断车牌添加是否小于月卡配置中的可绑定车牌数，如果小于则设置不置灰
      if (this.currentMontlyPackage.bindingCarNumber > this.addPlateNo.length) {
        this.isGreyPlateNo = false
      }
    },
    popParkNumber(id) {
      //点击删除车位时将车位从数组中移除
      this.addParkNumber.splice(
        this.addParkNumber.findIndex((item) => item === id),
        1
      )
      this.parkNumberList.splice(
        this.parkNumberList.findIndex((item) => item.id === id),
        1
      )
      // 判断车位添加是否小于月卡配置中的可绑定车位数，如果小于则设置不置灰
      if (this.currentMontlyPackage.bindingSpaceNumber > this.addParkNumber.length) {
        this.isGrey = false
      }
    },
    // 初始化车场信息
    initParkInfoList() {
      const that = this
      that.confirmLoading = true
      getMonthlyParkInfoList().then((res) => {
        if (res.success) {
          that.parkCodeList = []
          if (res.result) {
            res.result.forEach((parkInfo) => {
              that.parkCodeList.push({
                value: String(parkInfo.parkCode),
                label: parkInfo.parkName,
              })
            })
            if (!this.isEdit) {
              if (that.parkCodeList.length > 0) {
                let parkCode = that.parkCodeList[0].value
                let parkName = that.parkCodeList[0].label
                this.form.setFieldsValue({ parkCode: parkCode })
                this.form.setFieldsValue({ parkName: parkName })
              }
            }
            that.parkCodeChange(this.form.getFieldValue('parkCode'), '')
          }
        }
        that.confirmLoading = false
      })
    },
    // 初始化月卡绑定车位号
    initMonthlyCardBindParkNumber() {
      if (!this.monthlyCardInfo.id) {
        return
      }
      const that = this
      that.confirmLoading = true
      postAction(this.url.getUpateCarPlaceInfo, { id: this.monthlyCardInfo.id }).then((res) => {
        if (res.success) {
          console.log(res.result, '车位号信息')
          that.parkNumberList = res.result
          that.parkNumberPagination.total = res.result.length
          console.log(res.result.length, '车位号大于')

          if (res.result.length >= that.currentMontlyPackage.bindingSpaceNumber) {
            that.isGrey = true
          } else {
            that.isGrey = false
          }
          if (that.isEdit && that.currentMontlyPackage.bindingSpaceNumber === 1) {
            that.selectParkNumberName = that.parkNumberList[0].parkNumber
          }
        } else {
          that.parkNumberList = []
        }
        that.confirmLoading = false
      })
    },
    // 获取该月卡对应的车牌号集合
    initMonthlyCardBindPlateNo() {
      if (!this.monthlyCardInfo.id) {
        return
      }
      const that = this
      that.confirmLoading = true
      postAction(this.url.getUpatePlateNoInfo, { id: this.monthlyCardInfo.id }).then((res) => {
        if (res.success) {
          console.log(res.result, '车牌号集合')
          that.plateNoList = res.result
          that.addPlateNo = res.result.map((element) => element.plateNo)
          //获取原始车牌号集合
          that.sourceplateNoList = res.result.map((element) => element.plateNo)
          console.log(res.result.length, '数组长度')

          that.plateNoPagination.total = res.result.length
          if (res.result.length >= that.currentMontlyPackage.bindingCarNumber) {
            that.isGreyPlateNo = true
          } else {
            that.isGreyPlateNo = false
          }
          if (that.isEdit && that.currentMontlyPackage.bindingCarNumber === 1) {
            that.inputPlateNo = that.plateNoList[0].plateNo
          }
        } else {
          that.plateNoList = []
        }
        that.confirmLoading = false
      })
    },
    // 获取车场可用车位信息
    getParkFreeSpaceList(parkCode, throughAuthorityId) {
      if (!parkCode) {
        return
      }
      const that = this
      that.confirmLoading = true
      postAction(this.url.getParkFreeSpaceList, { parkCode: parkCode, throughAuthorityId: throughAuthorityId }).then(
        (res) => {
          that.parkNumberSelectList = [{ value: '', label: '请选择车位' }]
          if (res.success) {
            res.result.forEach((space) => {
              that.parkNumberSelectList.push({
                value: space.id,
                label: space.parkNumber + '-' + space.areaName,
              })
            })
            this.selectParkNumber = ''
          }
          that.confirmLoading = false
        }
      )
    },
    // 初始化月卡套餐
    initMonthlyPackageInfoList(parkCode) {
      if (!parkCode) {
        return
      }
      const that = this
      that.confirmLoading = true
      getAction(this.url.getMonthlyPackageList, { parkCode: parkCode }).then((res) => {
        if (res.success) {
          that.monthlyPackageInfoList = []
          if (res.result) {
            that.monthlyPackageInfoList = res.result
            let index = 0
            that.monthlyPackageInfoList.forEach((packageInfo) => {
              packageInfo.value = packageInfo.id
              packageInfo.label = packageInfo.packageName
              packageInfo.key = index
              index++
            })
            if (!this.isEdit) {
              if (that.monthlyPackageInfoList.length > 0) {
                this.form.setFieldsValue({ packageId: that.monthlyPackageInfoList[0].value })
                this.form.setFieldsValue({ packageName: that.monthlyPackageInfoList[0].label })
              }
              // else{
              //   this.form.setFieldsValue({ packageId: '' })
              //   this.form.setFieldsValue({ packageName: ''})
              // }
            }
          }
          this.monthlyPackageInfoChange()
          this.initMonthlyCardBindParkNumber()
          this.initMonthlyCardBindPlateNo()
        }
        that.confirmLoading = false
      })
    },
    // 获取车场可用集团权限组
    loadPermissionGroupList(parkCode) {
      const that = this
      if (!parkCode) {
        return
      }
      that.confirmLoading = true
      getAction(this.url.getPermissionGroupList, { parkCode: parkCode }).then((res) => {
        if (res.success) {
          that.permissionGroupList = [{ value: '', label: '默认全部权限' }]
          res.result.forEach((permissionGroup) => {
            that.permissionGroupList.push({
              label: permissionGroup.permissionName,
              value: permissionGroup.id,
            })
          })

          if (
            this.model.throughAuthorityId != null &&
            this.model.throughAuthorityId != '' &&
            this.model.throughAuthorityId != 'undefined'
          ) {
            this.form.setFieldsValue({ throughAuthorityId: this.model.throughAuthorityId })
            this.form.setFieldsValue({ throughAuthorityName: this.model.throughAuthorityName })
          } else {
            if (that.permissionGroupList.length <= 1) {
              this.form.setFieldsValue({ throughAuthorityId: '' })
              this.form.setFieldsValue({ throughAuthorityName: '默认全部权限' })
            } else {
              this.form.setFieldsValue({ throughAuthorityId: that.permissionGroupList[0].value })
              this.form.setFieldsValue({ throughAuthorityName: that.permissionGroupList[0].label })
            }
          }
        }
        that.confirmLoading = false
      })
    },
    // 初始化部门
    loadDepartmentTreeList(parkCode) {
      if (!parkCode) {
        return
      }
      const that = this
      that.confirmLoading = true
      postAction(this.url.getDepartmentList, { parkCode: parkCode }).then((res) => {
        if (res.success) {
          that.departTree = res.result
          if (!this.isEdit) {
            if (that.departTree.length > 0) {
              that.form.setFieldsValue({ monthlyDepartmentId: that.departTree[0].value })
              that.form.setFieldsValue({ monthlyDepartmentName: that.departTree[0].title })
            } else {
              this.form.setFieldsValue({ monthlyDepartmentId: '' })
              this.form.setFieldsValue({ monthlyDepartmentName: '' })
            }
          }
        }
      })
      that.confirmLoading = false
    },
    //月租套餐改变
    monthlyPackageInfoSelect(value, node) {
      // 选择套餐需要改变的车位号信息
      this.bindingSpaceNumber = 0
      this.isGrey = false
      this.parkNumberList = []
      this.addParkNumber = []
      this.selectParkNumber = ''

      // 选择套餐需要改变的车牌号信息
      this.bindingCarNumber = 0
      this.isGreyPlateNo = false
      this.addPlateNo = []
      this.plateNoList = []
      this.inputPlateNo = ''

      // let monthlyPackageInfo = this.monthlyPackageInfoList[node.key]
      // this.setFieldsValue({packageId:value})
      this.form.setFieldsValue({ packageName: node.componentOptions.children[0].text })
      this.monthlyPackageInfoChange()
    },
    //查询当前月租套餐对应的可绑定车位数和可绑定车牌数
    // getMonthlyPackageInfo(packageId){
    //   const that=this
    //   getAction(this.url.getPackageInfo,{id:packageId}).then((res) => {
    //     if (res.success) {
    //       that.bindingSpaceNumber = res.result.bindingSpaceNumber
    //       that.bindingCarNumber = res.result.bindingCarNumber
    //     } else {
    //       that.$message.warning(res.message)
    //     }
    //   })

    // },
    // 车场编号改变
    parkCodeChange(value, b) {
      if (b !== '') {
        this.form.setFieldsValue({ parkName: b.componentOptions.children[0].text })
      } else {
        this.form.setFieldsValue({ parkName: this.form.getFieldValue('parkName') })
      }
      if (!this.isEdit) {
        this.form.setFieldsValue({ carOwnerName: '' })
        this.form.setFieldsValue({ address: '' })
        this.form.setFieldsValue({ telephone: '' })
        this.form.setFieldsValue({ remark: '' })
        this.form.setFieldsValue({ monthlyMoney: '' })
        this.inputPlateNo = ''
      }
      let index = this.parkCodeList.findIndex((parkInfo) => {
        if (value === parkInfo.value) {
          return parkInfo
        }
      })
      this.title = this.form.getFieldValue('parkName') + '-开通月卡'
      this.initMonthlyPackageInfoList(value)
      this.loadDepartmentTreeList(value)
      this.loadPermissionGroupList(value)
      this.getParkFreeSpaceList(value, '')
    },
    // 通行权限修改
    throughAuthorityIdChange(a, b) {
      // this.getParkFreeSpaceList(this.form.getFieldValue('parkCode'), this.form.getFieldValue("throughAuthorityId"))
      let throughAuthorityName = b.componentOptions.children[0].text
      this.form.setFieldsValue({ throughAuthorityName: throughAuthorityName })
      this.getParkFreeSpaceList(this.form.getFieldValue('parkCode'), a)

      //清空已添加的车位
      this.bindingSpaceNumber = 0
      this.isGrey = false
      this.parkNumberList = []
      this.addParkNumber = []
      this.selectParkNumber = ''

      // 清空已添加的车牌
      this.bindingCarNumber = 0
      this.isGreyPlateNo = false
      this.addPlateNo = []
      this.plateNoList = []
      this.inputPlateNo = ''
    },
    // 车位编号
    parkNumberAdd() {
      if (this.selectParkNumber === '' || this.selectParkNumber === null || this.selectParkNumber === 'undefined') {
        this.$message.error('请选择车位')
        return
      }
      // 判断车位号是否已添加
      if (this.addParkNumber.findIndex((item) => item === this.selectParkNumber) > -1) {
        this.$message.error('该车位号已存在')
        return
      }
      this.addParkNumber.push(this.selectParkNumber)

      // 判断车位添加是否超过月卡配置中的可绑定车位数，如果超过则置灰添加按钮
      if (this.currentMontlyPackage.bindingSpaceNumber <= this.addParkNumber.length) {
        this.isGrey = true
      }

      let that = this
      //查询该车位的具体信息
      getAction(this.url.getParkSpaceById, { id: this.selectParkNumber }).then((res) => {
        if (res.success) {
          that.parkNumberList.push(res.result)
        } else {
          that.$message.warning(res.message)
        }
        that.confirmLoading = false
      })
    },

    checkPlateNumber(plateNo) {
      let exp =
        /(^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[ADF])|([ADF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$)/
      if (!exp.test(plateNo)) {
        return false
      } else {
        return true
      }
    },

    plateNoAdd() {
      if (this.inputPlateNo === '' || this.inputPlateNo === null || this.inputPlateNo === 'undefined') {
        this.$message.error('请输入车牌号')
        return
      }
      // 判断车牌号是否已添加
      if (this.addPlateNo.includes(this.inputPlateNo)) {
        this.$message.error('该车牌号已存在')
        return
      }
      // 验证车牌号是否正确
      let plateNo = this.inputPlateNo
      if (!this.checkPlateNumber(plateNo)) {
        this.$message.error('车牌号错误')
        return
      }

      this.addPlateNo.push(this.inputPlateNo)
      // 修改页面要新增的车牌号
      if (this.monthlyCardInfo.id != null && this.monthlyCardInfo.id != '' && this.monthlyCardInfo.id != 'undefined') {
        if (this.addPlateNos.indexOf(this.inputPlateNo) == -1) {
          this.addPlateNos.push(this.inputPlateNo)
          this.plateNoList.push(this.inputPlateNo)
        }
        // 去除要删除的车牌号
        if (this.deletePlateNos.indexOf(this.inputPlateNo) > -1) {
          this.deletePlateNos.splice(
            this.deletePlateNos.findIndex((item) => item === this.inputPlateNo),
            1
          )
        }
        if (this.plateNoList.indexOf(this.inputPlateNo) > -1) {
          this.plateNoList.splice(
            this.plateNoList.findIndex((item) => item === this.inputPlateNo),
            1
          )
        }
      }

      // 判断车牌号添加是否超过月卡配置中的可绑定车牌号，如果超过则置灰添加按钮
      if (this.currentMontlyPackage.bindingCarNumber <= this.addPlateNo.length) {
        this.isGreyPlateNo = true
      }

      this.plateNoList.push({ plateNo: this.inputPlateNo })
    },
    // 月卡套餐修改
    monthlyPackageInfoChange() {
      if (this.monthlyPackageInfoList.length == 0) {
        this.showHref = true
        this.instruction = '点击此处添加月卡套餐'
        this.showAllowHandleStarting = false
        this.showAllowHandleOf = false
        this.showCharges = false
        this.currentMontlyPackage = {}
        // this.$nextTick(() => {
        //   this.setFieldsValue({packageId: ''})
        //   this.setFieldsValue({packageName: ''})
        // })
        return
      } else {
        this.currentMontlyPackage = this.monthlyPackageInfoList.filter(
          (item) => item.value === this.form.getFieldValue('packageId')
        )[0]

        this.showHref = false

        this.instruction =
          '说明*：当前选择月租套餐为' +
          this.currentMontlyPackage.packageName+"，"+
          // this.currentMontlyPackage.bindingSpaceNumber +
          // '位' +
          // this.currentMontlyPackage.bindingCarNumber +
          // '车，' +
          '每' +
          (this.currentMontlyPackage.cycleLength === 1 ? '天' : '月') +
          parseFloat(this.currentMontlyPackage.charges / 100).toFixed(2) +
          '元。' +
          '允许添加' +
          this.currentMontlyPackage.bindingSpaceNumber +
          '个车位和' +
          this.currentMontlyPackage.bindingCarNumber +
          '个车牌'
      }

      if (this.plateNoList.length < this.currentMontlyPackage.bindingCarNumber) {
        this.isGreyPlateNo = false
      }
      if (this.monthlyCardInfo.id) {
        this.showCharges = true
        this.showAllowHandleStarting = true
        this.showAllowHandleOf = true
      }
      if (!this.monthlyCardInfo.id) {
        if (this.form.getFieldValue('monthlyMoney') != undefined || this.form.getFieldValue('monthlyMoney') != null) {
          this.form.setFieldsValue({ monthlyMoney: '' })
        }
        if (this.form.getFieldValue('beginTime') != undefined || this.form.getFieldValue('beginTime') != null) {
          this.form.setFieldsValue({ beginTime: '' })
        }
        if (this.form.getFieldValue('endTime') != undefined || this.form.getFieldValue('endTime') != null) {
          this.form.setFieldsValue({ endTime: '' })
        }

        var today = moment().format('YYYY-MM-DD')
        //昨天的时间
        var day1 = new Date()
        day1.setTime(day1.getTime() - 24 * 60 * 60 * 1000)
        var lastDay = moment(day1).format('YYYY-MM-DD')

        if (this.currentMontlyPackage.allowHandleStarting === 2 && this.currentMontlyPackage.allowHandleOf === 2) {
          this.showCharges = false
          this.showAllowHandleStarting = false
          this.showAllowHandleOf = false
          this.form.setFieldsValue({ beginTime: lastDay + ' ' + '23:59:59' })
          this.form.setFieldsValue({ endTime: lastDay + ' ' + '23:59:59' })
          this.form.setFieldsValue({ monthlyMoney: 0 })
          this.disableBeginTime = true
          this.disableEndTime = true
        }
        if (this.currentMontlyPackage.allowHandleStarting === 2 && this.currentMontlyPackage.allowHandleOf === 1) {
          this.showCharges = true
          this.showAllowHandleStarting = true
          this.showAllowHandleOf = true
          this.form.setFieldsValue({ beginTime: today + ' ' + '00:00:00' })
          this.disableBeginTime = true
          this.form.setFieldsValue({ endTime: today + ' ' + '23:59:59' })
          this.disableEndTime = false
        }
        if (this.currentMontlyPackage.allowHandleStarting === 1 && this.currentMontlyPackage.allowHandleOf === 2) {
          this.showCharges = true
          this.showAllowHandleStarting = true
          this.showAllowHandleOf = true
          this.form.setFieldsValue({ beginTime: today + ' ' + '00:00:00' })
          this.form.setFieldsValue({ endTime: today + ' ' + '23:59:59' })
          this.disableEndTime = true
          this.disableBeginTime = false
          // this.disabledStartDate(today + ' ' + "23:59:59")
        }
        if (this.currentMontlyPackage.allowHandleStarting === 1 && this.currentMontlyPackage.allowHandleOf === 1) {
          this.showCharges = true
          this.showAllowHandleStarting = true
          this.showAllowHandleOf = true
          this.disableBeginTime = false
          this.disableEndTime = false
        }
      }
    },
    // 新增
    add() {
      this.edit({})
    },
    // 编辑
    edit(record) {
      this.form.resetFields()
      const that = this
      this.reset()
      this.monthlyCardInfo = Object.assign({}, record)
      this.model = Object.assign({}, record)
      if (this.monthlyCardInfo.id != null && this.monthlyCardInfo.id != '' && this.monthlyCardInfo.id != undefined) {
        this.isGreyPark = true
        this.isGreyPackageInfo = true
        this.isGreyGroup = true
        this.isGreyBeginTime = true
        this.isGreyEndTime = true
        this.isGrey = true
        this.isGreyParkNumber = true

        this.isEdit = true
      } else {
        this.isGreyPark = true
        this.isGreyPackageInfo = false
        this.isGreyGroup = false
        this.isGreyBeginTime = false
        this.isGreyEndTime = false
        this.isGrey = false
        this.isGreyParkNumber = false

        this.isEdit = false
      }
      this.parkCode = this.monthlyCardInfo.parkCode
      this.visible = true
      this.$nextTick(() => {
        that.form.setFieldsValue(
          pick(
            this.model,
            'monthlyCode',
            'monthlyStatus',
            'carOwnerName',
            'address',
            'packageId',
            'packageName',
            'monthlyDepartmentId',
            'monthlyDepartmentName',
            'throughAuthorityId',
            'throughAuthorityName',
            'parkCode',
            'parkName',
            'telephone',
            'remark',
            'beginTime',
            'endTime',
            'monthlyMoney'
          )
        )
      })
      this.initParkInfoList()
    },
    reset() {
      this.form.resetFields()
      this.parkNumberList = []
      this.parkNumberSelectList = []
      this.selectParkNumber = ''
      this.addPlateNo = []
      this.addParkNumber = []
      this.deletePlateNos = []
      this.inputPlateNo = ''
      this.plateNoList = []
      this.parkCodeList = []
      this.monthlyPackageInfoList = []
      this.departTree = []
      this.permissionGroupList = []
      this.isGrey = false
      this.isGreyPlateNo = false
      this.addPlateNos = []

      this.showHref = false

      this.continueOpen = false
      this.selectParkNumberName=''
    },
    // 页面关闭
    close() {
      this.$emit('close')
      this.visible = false
    },

    delayConfirm(formDataConfirm, methodConfirm) {
      let that = this
      httpAction(that.url.delayConfirm, formDataConfirm, methodConfirm)
        .then((res) => {
          if (res.success) {
            if (res.result !== '' && res.result !== undefined && !that.isEdit) {
                that.noticeMsg = '系统当前存在场内车辆：' + res.result + '。请确认月租车开通方式！'
                that.takeEffectVisible = true
            } else {
              that.takeEffectVisible = false
              //无提示信息则直接开通
              that.openMonthlyCard()
              that.$emit('ok')
              // that.$message.warning(res.message)
            }
            that.$emit('ok')
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false

          if (!that.continueOpen) {
            that.close()
          }
        })
    },
    // 确定
    handleOk() {
      let that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err || Object.keys(err).length == 0) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''

          let formData = Object.assign(this.monthlyCardInfo, values)
          //时间格式化
          if (typeof formData.beginTime != 'string') {
            formData.beginTime = formData.beginTime ? formData.beginTime.format('YYYY-MM-DD') : null
          }
          if (typeof formData.endTime != 'string') {
            formData.endTime = formData.endTime ? formData.endTime.format('YYYY-MM-DD') : null
          }

          let formDataConfirm = {}
          let noticeMsg = ''
          if (!that.isEdit) {
            httpurl += that.url.add
            method = 'post'
            if (that.currentMontlyPackage.bindingCarNumber === 1 && that.inputPlateNo != '') {
              if(!that.checkPlateNumber(that.inputPlateNo)){
                that.$message.warning("车牌号错误")
                that.confirmLoading=false
                return
              }
              formData.plateNoList = [that.inputPlateNo]
            } else {
              formData.plateNoList = that.addPlateNo
            }
            if (that.currentMontlyPackage.bindingSpaceNumber === 1) {
              if (that.selectParkNumber != null && that.selectParkNumber != undefined && that.selectParkNumber != '') {
                formData.parkNumberList = [that.selectParkNumber]
              } else {
                that.$message.warning('请选择车位')
                that.confirmLoading = false
                return
              }
            } else {
              formData.parkNumberList = that.addParkNumber
            }

            if (formData.plateNoList.length <= 0) {
              that.$message.warning('请至少添加一个车牌')
              that.confirmLoading = false
              return
            }

            noticeMsg = '您确认开通本月租吗？'
            formDataConfirm.operationType = 1
          } else {
            // 添加要新增的车牌号
            // if (
            //   that.monthlyCardInfo.id != null &&
            //   that.monthlyCardInfo.id != '' &&
            //   that.monthlyCardInfo.id != 'undefined'
            // ) {
            if (that.currentMontlyPackage.bindingCarNumber === 1) {
              if(!that.checkPlateNumber(that.inputPlateNo)){
                that.$message.warning("车牌号错误")
                that.confirmLoading=false
                return
              }
              that.addPlateNo = [that.inputPlateNo]
            }
            that.addPlateNos = []
            if (that.addPlateNo.length > 0) {
              that.addPlateNo.filter(function (id) {
                if (!that.sourceplateNoList.includes(id)) {
                  that.addPlateNos.push(id)
                }
              })
            }
            formData.plateNoList = that.addPlateNos
            formData.addPlateNos = that.addPlateNos

            that.deletePlateNos = []
            if (that.sourceplateNoList.length > 0) {
              that.sourceplateNoList.filter(function (id) {
                if (!that.addPlateNo.includes(id)) {
                  that.deletePlateNos.push(id)
                }
              })
            }
            formData.deletePlateNos = that.deletePlateNos

            if (that.addPlateNo.length <= 0) {
              that.$message.warning('请至少添加一个车牌')
              that.confirmLoading = false
              return
            }
            // }

            httpurl += that.url.edit
            method = 'put'

            noticeMsg = '您确认修改该月租信息吗？'
            formDataConfirm.operationType = 2
          }

          if (
            formData.parkNumberList != null &&
            formData.parkNumberList.length < that.currentMontlyPackage.bindingSpaceNumber
          ) {
            that.$message.warning(
              '可添加车位数为：' +
                that.currentMontlyPackage.bindingSpaceNumber +
                '，请添加' +
                that.currentMontlyPackage.bindingSpaceNumber +
                '个车位'
            )
            that.confirmLoading = false
            return
          }
          //开始日期和结束日期添加时间
          if (formData.beginTime.indexOf(' ') === -1) {
            formData.beginTime = formData.beginTime + ' 00:00:00'
          }
          if (formData.endTime.indexOf(' ') === -1) {
            formData.endTime = formData.endTime + ' 23:59:59'
          }

          //判断时间选择的是否正确
          if (formData.beginTime > formData.endTime) {
            that.$message.warning('开始时间不能大于结束时间')
            that.confirmLoading = false
            return
          }
          // if(formData.monthlyMoney!=null&&formData.monthlyMoney!=undefined&&formData.monthlyMoney!=''){
          //   //传到后端时传分
          //   formData.monthlyMoney=Number(formData.monthlyMoney)*100
          // }
          that.httpurl = httpurl
          that.method = method
          that.formData = formData
          formDataConfirm = Object.assign(formDataConfirm, formData)
          //操作提示
          this.$confirm({
            title: '提示',
            content: noticeMsg,
            onOk() {
              //先判断该车是否已经开通过月租
              that.judgeIsOpenMonthlyCar(formDataConfirm)
            },
            onCancel() {
              that.confirmLoading = false
            },
          })
        }
        that.confirmLoading = false
      })
    },
    judgeIsOpenMonthlyCar(formDataConfirm) {
      let that = this
      httpAction(that.url.judegeIsOpenMonthlyCar, formDataConfirm, 'post')
        .then((res) => {
          if (res.success) {
            that.delayConfirm(formDataConfirm, 'post')
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false
        })
    },
    openMonthlyCard() {
      console.log(this.httpurl)
      const that = this
      if(this.isEdit){
        this.formData.isEffect = 1
      }
      httpAction(this.httpurl, this.formData, this.method)
        .then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.$emit('ok')
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false
          that.loading = false
          that.takeEffectVisible = false

          if (!that.continueOpen) {
            that.close()
          } else {
            that.edit({})
          }
        })
    },

    // 关闭
    handleCancel() {
      this.close()
    },
  },
}
</script>

<style lang="less" scoped>
.itemLabel::after {
  content: ':';
  position: relative;
  top: -0.5px;
  margin: 0 8px 0 2px;
  box-sizing: border-box;
}
.contentDetail {
  tr {
    td:first-child {
      text-align: right;
    }
  }
}
::v-deep .ant-modal-title {
  font-weight: 600;
}
</style>
